package TomcatRelated;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.ws.rs.core.MediaType;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;


import android.util.Log;

public class TomcatClient 
{
	//***************************************Class Variables*******************************************//


	private static TomcatClient _tomcatClient = null;
	private String tag = new String("TomcatClient");

	private final String _serverIP = new String("132.72.213.15");

	private final int _serverPort = 5001;


	//***************************************Constructors*******************************************//	

	private TomcatClient()
	{
	}


	//***************************************Public Methods*******************************************//


	public static TomcatClient getTomcatClient()
	{
		if(_tomcatClient == null)
			_tomcatClient = new TomcatClient();
		return _tomcatClient;
	}


	//used to send a message to the application server to Path=nameOfPage, containing list of parameters=listOfParameters
	public String sendMessage(String nameOfPage, List<NameValuePair> listOfParameters) 
	{
		HttpClient client = new DefaultHttpClient();
		HttpHost host = new HttpHost(this._serverIP, this._serverPort, "http");
		HttpPost postMessage = new HttpPost("/ApplicationServer/" + nameOfPage);	
		postMessage.setHeader("Content-Type", MediaType.TEXT_PLAIN);

		try 
		{
			if (listOfParameters != null){
				postMessage.setEntity(new UrlEncodedFormEntity(listOfParameters));
			}
			Log.v(tag , "trying to send "+nameOfPage+" request to server...");
			HttpResponse response = client.execute(host,postMessage);
			Log.v(tag , "message was sent!");

			// Check if server response is valid
			StatusLine status = response.getStatusLine();

			if (status.getStatusCode() != HttpStatus.SC_OK)
			{
				Log.v(tag , "Invalid response from server: " + status.toString());
			}
			else
			{
				String strResonse = getStringFromResponse(response); 
				Log.v(tag , "Server response: '" + strResonse + "'");

				//sending back the response so that the caller could process it.
				return strResonse;
			}


		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}

		//something went wrong!
		return null;
	}

	public InputStream getXml(String nameOfPage, List<NameValuePair> listOfParameters) 
	{
		HttpClient client = new DefaultHttpClient();
		HttpHost host = new HttpHost(this._serverIP, this._serverPort, "http");
		HttpPost postMessage = new HttpPost("/ApplicationServer/" + nameOfPage);

		postMessage.setHeader("Content-Type", MediaType.APPLICATION_XML);

		try 
		{
			if (listOfParameters != null){
				postMessage.setEntity(new UrlEncodedFormEntity(listOfParameters));
			}
			HttpResponse response = client.execute(host,postMessage);
			Log.v(tag , "message was sent.......");

			// Check if server response is valid
			StatusLine status = response.getStatusLine();

			if (status.getStatusCode() != HttpStatus.SC_OK)
			{
				Log.v(tag , "Invalid response from server: " + status.toString());
			}
			else
			{
				return response.getEntity().getContent();
			}

		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		//something went wrong!
		return null;
	}

	//***************************************Private Methods*******************************************//


	private String getStringFromResponse(HttpResponse response)
	{
		//		Log.v(tag, "pulling response");
		try{
			// Pull returnContent stream from response
			HttpEntity entity = response.getEntity();
			InputStream inputStream = null;
			try {
				inputStream = entity.getContent();
			} 
			catch (Exception e) 
			{
				Log.v(tag, e.toString());
			} 

			ByteArrayOutputStream returnContent = new ByteArrayOutputStream();

			// Read response into a buffered stream
			int readBytes = 0;
			byte[] sBuffer = new byte[512];
			try 
			{
				while ((readBytes = inputStream.read(sBuffer)) != -1) 
				{
					returnContent.write(sBuffer, 0, readBytes);
					//					Log.v(tag, readBytes + " bytes were read!");
				}
			} 
			catch (IOException e) 
			{
				e.printStackTrace();
			}
			return new String(returnContent.toByteArray());
		}
		catch(Exception E)
		{
			return null;
		}
	}
}
